package com.iot.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.iot.annotate.Authorize;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Authorize authorize = handlerMethod.getMethodAnnotation(Authorize.class);
            if (authorize == null) {
                //方法不存在则在类上寻找注解则在类上寻找注解
                authorize = handlerMethod.getBeanType().getAnnotation(Authorize.class);
            }

            //如果没有添加权限注解则直接跳过允许访问
            if (authorize == null) {
                return true;
            }
            String[] validateRoles = authorize.value();
            if (null == validateRoles) {
                return true;
            }
            //获取用户权限
            for (String validateRole : validateRoles) {
                StpUtil.checkPermission(validateRole);
            }
        }
        return true;
    }
}
